# optimized_functions.pyx

import numpy as np
cimport numpy as np
from libc.math cimport sqrt

def ts_argmax(np.ndarray[np.float64_t, ndim=2] x, int window=10):
cdef int n = x.shape[0]
cdef int m = x.shape[1]
cdef np.ndarray[np.float64_t, ndim=2] result = np.empty((n, m), dtype=np.float64)
cdef int i, j, k
cdef double max_val
cdef int argmax_idx

for i in range(n):
    for j in range(m):
        if i >= window - 1:
            max_val = x[i - window + 1, j]
            argmax_idx = 0
            for k in range(1, window):
                if x[i - window + 1 + k, j] > max_val:
                    max_val = x[i - window + 1 + k, j]
                    argmax_idx = k
            result[i, j] = argmax_idx + 1
        else:
            result[i, j] = np.nan
return result

def stddev(np.ndarray[np.float64_t, ndim=2] x, int window=10):
cdef int n = x.shape[0]
cdef int m = x.shape[1]
cdef np.ndarray[np.float64_t, ndim=2] result = np.empty((n, m), dtype=np.float64)
cdef int i, j, k
cdef double mean, sum_sq, val

for j in range(m):
    for i in range(n):
        if i >= window - 1:
            mean = 0.0
            sum_sq = 0.0
            for k in range(window):
                val = x[i - window + 1 + k, j]
                mean += val
            mean /= window
            for k in range(window):
                val = x[i - window + 1 + k, j]
                sum_sq += (val - mean) * (val - mean)
            result[i, j] = sqrt(sum_sq / (window - 1))
        else:
            result[i, j] = np.nan
return result
